package ui.activity.exchange;

import java.sql.SQLException;

import util.cardparse.ParseCardHelper;
import util.zxing.qrcodehelper.QRCodeHelper;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import business.entity.Card;
import business.service.card.ICardDetailViewService;
import business.service.card.impl.CardDetailViewService;

import com.google.zxing.WriterException;
import com.lab107team.R;

/**
 * @author Y_x
 * 
 */
public class CardQRCodeActivity extends Activity {

	private ImageButton btnGoBack = null;
	private ImageView ivQRCode = null;
	private TextView tvName = null;
	private ICardDetailViewService service = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.share_card_layout);

		init();
	}

	private void init() {
		btnGoBack = (ImageButton) findViewById(R.id.btn_share_card_back);
		btnGoBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		tvName = (TextView) findViewById(R.id.tv_share_card_name);
		ivQRCode = (ImageView) findViewById(R.id.iv_share_card_qrcode);

		Intent intent = getIntent();
		int id = intent.getIntExtra("id", -1);
		service = new CardDetailViewService(null);
		Card card = null;
		try {
			card = service.search(id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (card == null) {
			System.out.println("分享的对象不存在");
			finish();
			return;
		}
		tvName.setText(card.getName());
		// TODO 将Card生成String
		Point size = new Point();
		Display display = getWindow().getWindowManager().getDefaultDisplay();
		display.getSize(size);

		System.out.println("size = " + size.x);
		String msg = ParseCardHelper.encodeCard(card);
		Bitmap qrcode = null;
		try {
			qrcode = QRCodeHelper.write(msg, size.x, size.x);
		} catch (WriterException e) {
			System.out.println("生成失败");
		}
		if (qrcode != null) {
			ivQRCode.setImageBitmap(qrcode);
		}
	}
}
